package cn.mntool.fastcode.generate.utils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationContext;

/**
 * describe: spring上下文工具
 *
 * @author lianying
 * @date 2019/05/09
 */
public class SpringUtils {
    private static ApplicationContext context;

    /**
     * 设置上下文
     *
     * @param applicationContext
     */
    public static void setContext(ApplicationContext applicationContext) {
        context = applicationContext;
    }

    /**
     * 获取上下文
     *
     * @return
     */
    public static ApplicationContext getContext() {
        return context;
    }

    /**
     * 根据class类型获取bean
     *
     * @param beanClass
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> beanClass) {
        return context.getBean(beanClass);
    }

    /**
     * 根据bean名称获取bean
     *
     * @param beanName
     * @return
     */
    public static Object getBean(String beanName) {
        return context.getBean(beanName);
    }

    /**
     * 获取SPRING的全局配置文件值 如果key为空或key不存在，那么直接返回null
     *
     * @param key
     * @return
     */
    public static String getConfig(String key) {
        if (StringUtils.isBlank(key)) {
            return null;
        }
        return context.getEnvironment().getProperty(key);
    }
}
